package cn.laixueit.properties;

import cn.laixueit.commons.JwtUtils;
import cn.laixueit.commons.RsaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Component
@ConfigurationProperties(prefix = "leyou.jwt")
public class JwtProperties {
//    @Value("leyou.jwt.secret")
    private String secret; // 密钥

//    @Value("leyou.jwt.pubKeyPath")
    private String pubKeyPath;// 公钥

//    @Value("leyou.jwt.priKeyPath")
    private String priKeyPath;// 私钥

//    @Value("leyou.jwt.expire")
    private int expire;// token过期时间

    private PublicKey publicKey; // 公钥

    private PrivateKey privateKey; // 私钥

    private String tokenName;


    private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);


    @PostConstruct
    public void init(){
        try {
            File pubKeyPath = new File(this.pubKeyPath);
            File priKeyPath = new File(this.priKeyPath);
            if(!pubKeyPath.exists() || !priKeyPath.exists()){
                // 如果两个里面有一个不存在则创建
                RsaUtils.generateKey(this.pubKeyPath,this.priKeyPath,secret);
            }
            // 获取公钥和私钥
            this.publicKey = RsaUtils.getPublicKey(this.pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(this.priKeyPath);
        } catch (Exception e) {
            logger.error("获取公钥或私钥失败！");
            e.printStackTrace();
        }
    }

    public String getTokenName() {
        return tokenName;
    }

    public void setTokenName(String tokenName) {
        this.tokenName = tokenName;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getPubKeyPath() {
        return pubKeyPath;
    }

    public void setPubKeyPath(String pubKeyPath) {
        this.pubKeyPath = pubKeyPath;
    }

    public String getPriKeyPath() {
        return priKeyPath;
    }

    public void setPriKeyPath(String priKeyPath) {
        this.priKeyPath = priKeyPath;
    }

    public int getExpire() {
        return expire;
    }

    public void setExpire(int expire) {
        this.expire = expire;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(PublicKey publicKey) {
        this.publicKey = publicKey;
    }

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(PrivateKey privateKey) {
        this.privateKey = privateKey;
    }
}
